#! /bin/bash
# set -x

_trim (){
	eval trimVar="\${$1}"
	trimVar=$(echo $trimVar | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
	eval $1=\$trimVar
}

_log () {
	messageID="$1"
	echo "${messageID}" >> $db_file
}

_warning () {
	messageID="$1"
	
	cMessage="$(_current_date) ${TR_TORRENT_NAME} ${messageID}"
	echo "${cMessage}" >> sed_install_dir/TRsmf.err
}

_current_date () {
      date '+%Y-%m-%d %H:%M:%S'
}

# BOUCLE FILMS #
_main_movie () {
	type=movie

	# Copie du fichier & log
	cp "${TR_TORRENT_DIR}/${line}" "$movies_dir/$fileName" ; chmod 0775 "$movies_dir/$fileName"
	_log "$(_current_date) ${TR_TORRENT_NAME};${type};cp ${fileName};${movies_dir}"
}

# BOUCLE TVSHOW
_main_tvshow () {
	type=tvshow
	
	tvShowName=$(echo "$fileName" | awk -F${sepField} '{print $1}' | tr [A-Z] [a-z] | sed -e 's#[-,._]# #g' -e 's#^a ##g' -e 's#^the ##g')
	_trim tvShowName
	
	tvShowDir=$(grep -w "$tvShowName" $hach_file | awk -F\-\> '{print $2}')
	_trim tvShowDir

	# Controle si la serie existe
	if [ x"$tvShowDir" = "x" ] ; then
		tvshowNameDot=$(echo "$tvShowName" | sed 's# #.#g' )
		# AJOUT TVSHOW DANS HACH FILE
		echo "$tvShowName -> $tvshows_dir/$tvshowNameDot" >> $hach_file

		# CREATION REPERTOIRE TVSHOW
		tvShowDir="$tvshows_dir/$tvshowNameDot"
		if [ ! -d "$tvshows_dir/$tvshowNameDot" ] ; then
			mkdir "$tvshows_dir/$tvshowNameDot"
			chmod 0775 "$tvshows_dir/$tvshowNameDot"
		fi
		# Logs
		_log "$(_current_date) ${type};mkdir ${tvshowNameDot};${TR_TORRENT_NAME}"
	fi

	# Copie du fichier & log
	cp "${TR_TORRENT_DIR}/${line}" "$tvShowDir/$fileName" && chmod 0775 "$tvShowDir/$fileName"
	_log "$(_current_date) ${TR_TORRENT_NAME};${type};cp ${fileName};${tvShowDir}"
}


###################
# Debut
###################
# Source fichier de conf.
confFile=sed_install_dir/TRsmf.conf
[ ! -f ${confFile} ] && _warning "fichier de conf non present : ${confFile}" && exit 1
. ${confFile}
CR=$?
[ $CR != 0 ] && _warning "Pb export du fichier de conf : ${confFile} " && exit 1

# Varible
# TR_TORRENT_NAME
# TR_TORRENT_DIR
# TR_TORRENT_ID
# TR_TORRENT_HASH
# TR_APP_VERSION
# TR_TIME_LOCALTIME 
mySupportFile=`echo "$support_file$" | sed 's/,/$|/g'`

# Boucle principale : Film / TVShow
# Get torrrent file
/usr/bin/transmission-remote -t${TR_TORRENT_ID} --files | grep ": 100%" | grep -E "$mySupportFile$" | cut -c35- | while read line ; do
	# trim $line & file name
	fileName=$(echo $line| awk -F\/ '{print $NF}')

	CR=1
	# Controle tvshow
	for i in $regexp ; do
		echo "$fileName" | grep -q "$i"
		CR=$?
		if [ $CR = 0 ] ; then
			sepField=$(echo "$i" | sed 's/\\//g')
			_main_tvshow
			break
		fi
	done
	
	# Controle movie
	[ $CR = 1 ] && _main_movie
	
done